﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Program09
{
    class Program
    {
        static void Main(string[] args)
        {
            #region 文件读取和写入
            //using (FileStream file = new FileStream("aaa", FileMode.Create, FileAccess.Write))
            //{
            //    var str = "axb";

            //    将字符串转换成二进制
            //    byte[] buffer = Encoding.UTF8.GetBytes(str);
            //    file.Write(buffer, 0, buffer.Length);

            //}
            //Console.WriteLine("文件写入成功");

            //读取文件
            //FileStream fsRead = new FileStream(@"G:\Gitee\CsharpAdvanced\Program09\bin\Debug\aaa", FileMode.OpenOrCreate, FileAccess.Read);

            ////读取文件大小不超过5m
            //byte[] buffer = new byte[1024 * 1024 * 5];

            ////读取当前文件的有效字符
            //int r = fsRead.Read(buffer, 0, buffer.Length);

            ////将读出的二进制转换成utf-8格式的字符串
            //string str = Encoding.UTF8.GetString(buffer, 0, r);
            //fsRead.Close();
            //fsRead.Dispose();
            //Console.WriteLine(str);
            #endregion

            var source = "a.txt";
            var target = "b.txt";
            CopyFile(source, target);
            Console.WriteLine("文件Copy成功");

            Console.ReadLine();
        }

        public static void CopyFile(string source,string targt)
        {
            //读取文件
            using (FileStream fsRead = new FileStream(source, FileMode.OpenOrCreate, FileAccess.Read))
            {
                //写入文件
                using (FileStream fsWrite = new FileStream(targt, FileMode.OpenOrCreate, FileAccess.Write))
                {
                    //读写文件的缓冲区
                    byte[] buffer = new byte[1024 * 1024 * 10];

                    //用循环读取文件，如果源文件大于缓冲区，会反复读取
                    while (true)
                    {
                        //返回本次读取的实际字节数
                        int r = fsRead.Read(buffer, 0, buffer.Length);
                        //如果读取到0，跳出循环
                        if (r == 0)
                        {
                            break;
                        }
                        //写入文件
                        fsWrite.Write(buffer, 0, r);
                    }
                }
            }           
        }
    }
}
